package fr.upmc.i3s.upmcontact.views.connection;

import com.parse.Parse;
import com.parse.ParseAnalytics;

import fr.upmc.i3s.upmcontact.R;
import fr.upmc.i3s.upmcontact.backend.BackEndBridge;
import fr.upmc.i3s.upmcontact.backend.BackEndBridgeImpl;
import fr.upmc.i3s.upmcontact.callbacks.ISignInCallback;
import fr.upmc.i3s.upmcontact.contents.User;
import fr.upmc.i3s.upmcontact.listeners.OnConnectionChangeListener;
import fr.upmc.i3s.upmcontact.tools.MobileDataUtils;
import fr.upmc.i3s.upmcontact.tools.PreferencesManager;
import fr.upmc.i3s.upmcontact.views.FragmentController;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class SignInActivity extends Activity {
	
	private Handler handler;
	private BackEndBridge backEndInstance;
	
	private ImageView ivConnectivity;
	private EditText etUserName;
	private EditText etPassword;
	private CheckBox cbKeepMeSigned;
	private Button bSignIn;
	private Button bSignUp;
	private TextView tvInformations;
	
	private OnConnectionChangeListener connectivityListener;
	private boolean listenerRegistered;
	

	  ////////////////////
	 // INITIALIZATION //
	////////////////////
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		listenerRegistered = false;
		this.handler = new Handler();
		backEndInit();
		customizeActionBar();
		if(checkAutoSignin() == true) {
			if(BackEndBridgeImpl.getInstance(this).getCurrentUser() == null) {
				if(MobileDataUtils.isNetworkAvailable(this)) {
					backEndInstance.signin(signInCallback);
				} else {
					Toast.makeText(SignInActivity.this, R.string.signed_but_offline, Toast.LENGTH_LONG).show();
					Intent intent = new Intent(SignInActivity.this, FragmentController.class);
					startActivity(intent);
					finish();
				}
			} else {
				Intent intent = new Intent(SignInActivity.this, FragmentController.class);
				startActivity(intent);
				finish();
			}
		} else {
			connectivityListener = new OnConnectionChangeListener(ivConnectivity, null);
			setContentView(R.layout.activity_signin);
			fetchViews();
			setUsernameIfNeeded();
			setListeners();
		}
	}
	
	@Override 
	protected void onDestroy() {
		super.onDestroy();
		if(listenerRegistered) {
			unregisterReceiver(connectivityListener);
			listenerRegistered = false;
		}
	}
	
	private void customizeActionBar() {
		this.setTitle("");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayShowTitleEnabled(false);
		getActionBar().setDisplayUseLogoEnabled(false);
		getActionBar().setCustomView(R.layout.layout_action_bar);
		getActionBar().setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.textView_title_activity);
		title.setText(getString(R.string.title_activity_signin));
		ImageView toggle = (ImageView) findViewById(R.id.imageView_toggle_menu);
		toggle.setVisibility(View.GONE);
		ivConnectivity = (ImageView) findViewById(R.id.imageView_connectivity);
	}
	
	
	private void backEndInit() {
		Parse.initialize(this, BackEndBridgeImpl.APPLICATION_ID, BackEndBridgeImpl.CLIENT_KEY);
		ParseAnalytics.trackAppOpened(getIntent());
		this.backEndInstance = BackEndBridgeImpl.getInstance(this);
		this.backEndInstance.reinitBackEnd(this);
	}
	
	
	private boolean checkAutoSignin() {
		User user = PreferencesManager.getSignInSettings(this);
		if(!user.isKeepLogged()) { 
			return false;
		}
		if(user.getUsername() == null || user.getPassword() == null) {
			return false;
		}
		return true;
	}
	
	
	public void setUsernameIfNeeded() {
		Bundle extras = getIntent().getExtras();
		if(extras != null) {
			String username = extras.getString("username");
			if(username != null && !username.equals("")) {
				this.etUserName.setText(username);
				this.handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						// request focus on password edittext
						etPassword.requestFocus();
						// show keyboard
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
					}
				}, 50);
			}
		}
	}
	
	
	public void fetchViews() {
		this.etUserName = (EditText) findViewById(R.id.editText_login);
		this.etPassword = (EditText) findViewById(R.id.editText_password);
		this.cbKeepMeSigned = (CheckBox) findViewById(R.id.checkBox_keepmesigned);
		this.bSignIn = (Button) findViewById(R.id.button_signIn);
		this.bSignUp = (Button) findViewById(R.id.button_signUp);
		this.tvInformations = (TextView) findViewById(R.id.textView_infos_signin);
	}
	
	
	public void setListeners() {
		this.bSignIn.setOnClickListener(onSignInClickListener); 	// Sign In button
		this.bSignUp.setOnClickListener(onSignUpClickListener); 	// Sign Up button
		this.etUserName.setOnTouchListener(onTouchListenerAdapter); // Username edittext
		this.etPassword.setOnTouchListener(onTouchListenerAdapter); // Password edittext
		registerReceiver(connectivityListener, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
		listenerRegistered = true;
	}
	
	
	  ///////////////
	 // CALLBACKS //
	///////////////
	
	@Override
	public void onBackPressed() {
	    new AlertDialog.Builder(this)
	        .setTitle(R.string.really_exit)
	        .setMessage(R.string.really_exit_msg)
	        .setNegativeButton(android.R.string.no, null)
	        .setPositiveButton(android.R.string.yes, new android.content.DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface arg0, int arg1) {
	                SignInActivity.super.onBackPressed();
	            }
	        }).create().show();
	}
	
	public ISignInCallback signInCallback = new ISignInCallback() {
		@Override
		public void signed(boolean success) {
			if(success) {
				// close keyboard :
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(etUserName.getWindowToken(), 0);
				imm.hideSoftInputFromWindow(etPassword.getWindowToken(), 0);
				// open fragment controller
				Toast.makeText(SignInActivity.this, R.string.success_sign_in, Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(SignInActivity.this, FragmentController.class);
				startActivity(intent);
				finish();
			} else {
				SignInActivity.this.setContentView(R.layout.activity_signin);
				((SignInActivity) SignInActivity.this).fetchViews();
				((SignInActivity) SignInActivity.this).setListeners();
			}
		}
	};
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private OnClickListener onSignInClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String username = etUserName.getText().toString();
			if(username == null || username.equals("") || username.equals(" ")) {
				etUserName.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_wrong_login);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			String password = etPassword.getText().toString();
			if(password == null || password.equals("") || password.equals(" ")) {
				etPassword.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_wrong_password);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			boolean keepSigned = cbKeepMeSigned.isChecked();
			User user = new User(null, null, null, username, password, null, keepSigned);
			PreferencesManager.saveSignInSettings(SignInActivity.this, user);
			backEndInstance.signin(user, signInCallback);
		}
	};
	
	private OnClickListener onSignUpClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
			startActivity(intent);
			finish();
		}
	};
	
	private OnTouchListener onTouchListenerAdapter = new OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent arg1) {
			if(view instanceof EditText) {
				EditText etView = (EditText) view;
				etView.setTextColor(Color.BLACK);
				tvInformations.setText("");
				tvInformations.setVisibility(View.GONE);
			}
			return false;
		}
	};
	
}
